package vip.xiaonuo.facedoor.iservice.issulog;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.facedoor.modular.synchronizelog.entity.SynchronizeLog;
import vip.xiaonuo.facedoor.modular.synchronizelog.service.SynchronizeLogService;

import java.util.Date;

@Service
public class DeviceLogService {

    @Autowired
    private SynchronizeLogService synchronizeLogService;

    public void addMemberLog(String name, String deviceBaseName, String returnJson, Integer synchroRes, Integer type) {
        SynchronizeLog synchronizeLog = new SynchronizeLog();
        synchronizeLog.setMemberType(1).setType(type).setDeviceName(deviceBaseName).setName(name).setSynchroDate(new Date()).setCreateDate(new Date());
        synchronizeLog.setSynchroRes(synchroRes);
        synchronizeLog.setRetMessage(JSON.toJSONString(returnJson));
        synchronizeLogService.save(synchronizeLog);
    }


    public void addVisitorLog(String name, String deviceBaseName, String returnJson, Integer synchroRes, Integer type) {
        SynchronizeLog synchronizeLog = new SynchronizeLog();
        synchronizeLog.setMemberType(2).setType(type).setDeviceName(deviceBaseName).setName(name).setSynchroDate(new Date()).setCreateDate(new Date());
        synchronizeLog.setSynchroRes(synchroRes);
        synchronizeLog.setRetMessage(JSON.toJSONString(returnJson));
        synchronizeLogService.save(synchronizeLog);
    }


    public void addDeviceLog(String name, String deviceName, String req, Integer cmd, String serialNumber) {
        SynchronizeLog synchronizeLog = new SynchronizeLog();
        synchronizeLog.setMemberType(3).setName(name).setType(cmd).setDeviceName(deviceName).setSynchroDate(new Date()).setCreateDate(new Date()).setReqMessage(req).setSerialNumber(serialNumber);
        synchronizeLogService.save(synchronizeLog);
    }

    public void updateDeviceLog(Long serialNumber, String ackMessage, String ackResult) {
        SynchronizeLog synchronizeLog = synchronizeLogService.getOne(new LambdaQueryWrapper<SynchronizeLog>().eq(SynchronizeLog::getSerialNumber, serialNumber));
        synchronizeLog.setRetMessage(ackMessage);
        synchronizeLog.setSynchroRes(StringUtils.isNotBlank(ackResult) && (ackResult.equals("0000") || ackResult.equals("0201")) ? 1 : 2);
        synchronizeLog.setSynchroDate(new Date());
        synchronizeLogService.updateById(synchronizeLog);
    }
}
